package org.qcit.plugin

import com.android.build.gradle.AppExtension
import com.android.build.gradle.AppPlugin
import com.android.build.gradle.api.ApplicationVariant
import org.gradle.api.Action
import org.gradle.api.DomainObjectSet
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.qcit.plugin.Extension
import org.qcit.plugin.tasks.PgyerUploadTask
import org.qcit.plugin.tasks.SendMsgToDingTalkTask

class AutoPlugin implements Plugin<Project> {
    public static final String ANDROID_EXTENSION_NAME ="android";
    public static final String sPluginExtensionName ="releaseHelper";
    @Override
    public void apply(Project rootproject) {
        System.out.println("插件开始工作了");
        if (!rootproject.getPlugins().hasPlugin(AppPlugin.class)){
            throw new GradleException("无法在非android application插件中使用插件");
        }
        rootproject.getExtensions().create(sPluginExtensionName, Extension.class,rootproject);
        rootproject.afterEvaluate(new Action<Project>() {
            @Override
            public void execute(Project project) {
//                   for (Task task : project.getTasks()) {
//                       System.out.println("==============task name ======================"+task.getName());
//                   }
                System.out.println("==============execute======================");
                DomainObjectSet<ApplicationVariant> appVariants = ((AppExtension) project.getExtensions().findByName(ANDROID_EXTENSION_NAME)).getApplicationVariants();
                for (ApplicationVariant variant:appVariants){
                    System.out.println("==============for======================");
                    if (variant.getBuildType().getName().equalsIgnoreCase("release")){
                        System.out.println("==============release======================");
                        String variantName = variant.getName().substring(0,1).toUpperCase() + variant.getName().substring(1);
                        //上传文件到蒲公英托管
                        PgyerUploadTask pgyerUploadTask = project.getTasks().create("pgyUploadFor" + variantName,PgyerUploadTask.class);
                        pgyerUploadTask.init(variant,project);
                        //发送消息到钉钉
                        SendMsgToDingTalkTask sendMsgToDingTalkTask = project.getTasks().create("sendMsgToDingTalkFor"+variantName,SendMsgToDingTalkTask.class);
                        sendMsgToDingTalkTask.init(variant,project);
                        //设置任务依赖关系  顺序
                        variant.getAssembleProvider().get().dependsOn(project.getTasks().findByName("clean"));
                        pgyerUploadTask.dependsOn(variant.getAssembleProvider().get());
                        sendMsgToDingTalkTask.dependsOn(pgyerUploadTask);
                    }
                }
            }
        });
    }
}
